package com.tiantianyuegou.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tiantianyuegou.R;
import com.tiantianyuegou.adapter.CollectionGoodsAdapter;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.http.SPHelper;
import com.tiantianyuegou.model.GoodsModel;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.NetworkUtils;
import com.tiantianyuegou.util.ToastUtils;
import com.tiantianyuegou.util.Tools;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 收藏界面
 */
public class MyCollectionActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {

    private ImageView img_title;
    private TextView text_title;
    private PullToRefreshGridView grid_collection;

    private ImageView img_collection;
    private TextView text_collection;

    private boolean isRefresh, isLoadMore;
    private CollectionGoodsAdapter goodsAdapter;
    List<GoodsModel> datas;
    LoadingDialog loadingDialog;
    private int mPage = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_collection);
        init();
       Tools.changeSystemBar(this);
    }


    private void init() {
        text_title = (TextView) findViewById(R.id.text_title);
        img_title = (ImageView) findViewById(R.id.img_title);
        text_title.setText("我的收藏");
        img_title.setOnClickListener(this);

        img_collection = (ImageView) findViewById(R.id.img_collection);
        text_collection = (TextView) findViewById(R.id.text_collection);

        img_collection.setVisibility(View.GONE);
        text_collection.setVisibility(View.GONE);
        grid_collection = (PullToRefreshGridView) findViewById(R.id.grid_collection);
        grid_collection.setVisibility(View.VISIBLE);
        datas = new ArrayList<>();

//        grid_collection.setSelection(R.color.transgray);
        grid_collection.setOnItemClickListener(this);
        grid_collection.setMode(PullToRefreshBase.Mode.BOTH);
        grid_collection.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
                isRefresh = true;
                isLoadMore = false;
                doCollectList(1);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
                isLoadMore = true;
                isRefresh = false;
                doCollectList((++mPage));
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        isRefresh = true;
        isLoadMore = false;
        loadingDialog = new LoadingDialog(MyCollectionActivity.this);
        loadingDialog.show();
        doCollectList(1);//调收藏列表接口
        loadingDialog.dismiss();
    }

    /**
     * 调收藏列表接口
     */
    private void doCollectList(int page) {
        if (!NetworkUtils.isNetworkAvailable(this)) {

         ToastUtils.showToast(this, "请检查您的网络");
        }
        RequestParams params = new RequestParams();
        params.addBodyParameter("tmId", SPHelper.getTmId());
        params.addBodyParameter("page", "" + page);
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.COLLECT_LIST, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                System.out.println(responseInfo.result);
                loadingDialog.dismiss();
                grid_collection.onRefreshComplete();
                String root = responseInfo.result;
                try {
                    JSONObject rootObj = new JSONObject(root);
                    String code = rootObj.getString("code");
                    if (code.equalsIgnoreCase("100")) {

                        String list = rootObj.getString("list");
                        if (list.contains("[")) {
                            if (isRefresh) {
                                datas.clear();
                                isRefresh = false;
                            } else if (isLoadMore) {
                                isLoadMore = false;
                            }
                            JSONArray listArray = new JSONArray(list);
                            for (int i = 0; i < listArray.length(); i++) {
                                JSONObject listObj = listArray.getJSONObject(i);
                                String tpId = listObj.getString("tpId");
                                String tpName = listObj.getString("tpName");
                                String tpSalePrice = listObj.getString("tpSalePrice");
                                int tpIsDiscount = listObj.getInt("tpIsDiscount");
                                double tpDiscountPrice = listObj.getDouble("tpDiscountPrice");
                                int tpIsDeduction = listObj.getInt("tpIsDeduction");
                                int tpDeduction = listObj.getInt("tpDeduction");
                                int tpRedCount = listObj.getInt("tpRedCount");
                                int tpSalesCount = listObj.getInt("tpSalesCount");
                                String tpPics = listObj.getString("tpPic");
                                String tpPic = tpPics.split(",")[0];
                                GoodsModel model = new GoodsModel(tpId, tpName, tpSalePrice, tpPic);
                                datas.add(model);
                            }
                            goodsAdapter = new CollectionGoodsAdapter(MyCollectionActivity.this, datas, new CollectionGoodsAdapter.Callback() {
                                @Override
                                public void cancelCollect(int position) {
                                    doDelete(position);//删除收藏的商品
                                }
                            });
                            grid_collection.setAdapter(goodsAdapter);
                            goodsAdapter.notifyDataSetChanged();
                        }
                        grid_collection.setMode(PullToRefreshBase.Mode.BOTH);
                    } else {
                        if (datas.size() == 0&&!isLoadMore) {
                            grid_collection.setMode(PullToRefreshBase.Mode.DISABLED);
                            img_collection.setVisibility(View.VISIBLE);
                            text_collection.setVisibility(View.VISIBLE);
                            grid_collection.setVisibility(View.GONE);

                        }
                        if (isLoadMore) {
                            showMsg("没有更多数据");
                            isLoadMore = false;
                        }
                        grid_collection.setMode(PullToRefreshBase.Mode.PULL_DOWN_TO_REFRESH);

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    if (isRefresh) {
                        isRefresh = false;
                    } else if (isLoadMore) {
                        isLoadMore = false;
                        mPage--;
                        if (mPage == 0) {
                            img_collection.setVisibility(View.VISIBLE);
                            text_collection.setVisibility(View.VISIBLE);
                            grid_collection.setVisibility(View.GONE);
                        }
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                showMsg("请求服务器失败");
                img_collection.setVisibility(View.VISIBLE);
                text_collection.setVisibility(View.VISIBLE);
                grid_collection.setVisibility(View.GONE);
                loadingDialog.dismiss();
                grid_collection.onRefreshComplete();
            }
        });
    }

    /**
     * 删除收藏
     *
     * @param position
     */
    private void doDelete(final int position) {
        if (!NetworkUtils.isNetworkAvailable(this)) {
            ToastUtils.showToast(this, "请检查您的网络");
        }
        loadingDialog = new LoadingDialog(MyCollectionActivity.this);
        loadingDialog.setMsg("loading....");
        loadingDialog.show();
        System.out.println("------------" + datas.get(position).getTpId());
        RequestParams params = new RequestParams();
        params.addBodyParameter("tmId", SPHelper.getTmId());
        params.addBodyParameter("tpId", datas.get(position).getTpId());
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.DELTE_COLLECT, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                loadingDialog.dismiss();
                System.out.println(responseInfo.result + "------");
                String root = responseInfo.result;
                try {
                    JSONObject rootObj = new JSONObject(root);
                    String code = rootObj.getString("code");
                    if (code.equalsIgnoreCase("100")) {
                        showMsg("已取消收藏");
                        datas.remove(position);
                        goodsAdapter.notifyDataSetChanged();
                        if (datas.size() == 0) {
                            img_collection.setVisibility(View.VISIBLE);
                            text_collection.setVisibility(View.VISIBLE);
                            grid_collection.setVisibility(View.GONE);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    showMsg("服务器解析失败");
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {
                showMsg("请求服务器失败");
                loadingDialog.dismiss();
            }
        });

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_title:
                finish();
                break;
            default:
                break;
        }

    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Intent intent = new Intent(MyCollectionActivity.this, GoodsDetailActivity.class);
        String tpid = datas.get(i).getTpId();
        String tpPic=datas.get(i).getGoodsPhoto();
        intent.putExtra("tpId", tpid);
        intent.putExtra("tpPic",tpPic);;
        intent.putExtra("type","MyCollectionActivity");
        intent.putExtra("type","MyCollectionActivity");
        startActivity(intent);
    }


    @Override
    public void findViewByIds() {

    }

    @Override
    public void initListener() {

    }

    @Override
    public void initData() {

    }
}
